const express = require('express')
const fetchUrl = require('fetch').fetchUrl
const app = express()

app.set('view engine', 'ejs')
app.get('/', (req, res) => {
  // 获取双色球中奖数据
  fetchUrl('https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo=1&pageSize=30&week=&systemType=PC', (error, meta, result) => {
    if (error) {
      res.render('error',{
        error,
        html: ''
      })
      return;
    }
    if(result.toString().includes('!doctype html')){
      res.render('error', {
        html:result.toString(),
        error: ''
      })
      return;
    }
    const resData = JSON.parse(result.toString());
    let svgLines = {};
    const content = resData.result.map((item, index) => {
      item.red = item.red ? item.red.split(',') : []
      item.blue = parseInt(item.blue)
      item.redIdxs = item.red.map(item => {
        return parseInt(item)
      })
      let xstart = 100 - 20 / 2
      let xstep = 20
      let ystart = 23.33 * 2
      let ystep = 24

      if (!svgLines.redXyPoints) {
        svgLines.redXyPoints = {
          1: [
            `${xstart + (item.redIdxs[0] * xstep)},${ystart}`
          ],
          2: [
            `${xstart + (item.redIdxs[1] * xstep)},${ystart}`
          ],
          3: [
            `${xstart + (item.redIdxs[2] * xstep)},${ystart}`
          ],
          4: [
            `${xstart + (item.redIdxs[3] * xstep)},${ystart}`
          ],
          5: [
            `${xstart + (item.redIdxs[4] * xstep)},${ystart}`
          ],
          6: [
            `${xstart + (item.redIdxs[5] * xstep)},${ystart}`
          ]
        }
      } else {
        Object.keys(svgLines.redXyPoints).forEach((key, index) => {
          svgLines.redXyPoints[key].push(`${xstart + (item.redIdxs[index] * xstep)},${ystart + (svgLines.redXyPoints[key].length * ystep)}`)
        })
      }
      if (!svgLines.blueXyPoints) {
        svgLines.blueXyPoints = [
          `${xstart + (33 + parseInt(item.blue)) * xstep},${ystep*2}`
        ]
      }else{
        svgLines.blueXyPoints.push(`${xstart + (33 + parseInt(item.blue)) * xstep},${(index + 1) * ystep + ystep}`)
      }
      return item;
    })

    res.render('index', {
      pageInfo: {
        pageNo: resData.pageNo,
        pageSize: resData.pageSize,
        total: resData.total
      },
      redLines: Object.values(svgLines.redXyPoints).reduce((prev, item) => {
        prev.push(item.join(' '))
        return prev;
      }, []),
      redPoints: Object.values(svgLines.redXyPoints).reduce((prev, item) => {
        prev.push(item)
        return prev;
      }, []),
      linesColor: ['#B87333', '#9932CD', '#545454', '#C0D9D9', '#2F2F4F', '#FF2400'],
      blueLiens: svgLines.blueXyPoints.join(' '),
      content
    })
  })
})

app.listen(3000, () => {
  console.log('服务启动: http://localhost:3000/')
})